/**
 * 
 */
package org.demetra.core;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangPid;
import com.ericsson.otp.erlang.OtpErlangString;
import com.ericsson.otp.erlang.OtpErlangTuple;

/**
 * @author vvorobyov
 *
 */
public class JetsException extends RuntimeException {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6390384790804224L;
	private OtpErlangObject _reason;

	/**
	 * 
	 */
	public JetsException() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param message
	 */
	public JetsException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param cause
	 */
	public JetsException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}
	/**
	 * @param cause
	 */
	public JetsException(Throwable cause,OtpErlangObject aReason) {
		super(cause);
		_reason = aReason;
	}
	/**
	 * @param cause
	 */
	public JetsException(OtpErlangObject aReason) {
		_reason = aReason;
	}

	/**
	 * @param message
	 * @param cause
	 */
	public JetsException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}
	
	public OtpErlangObject toOtpObject(OtpErlangPid otpErlangPid) {
		if(_reason!=null)
			return toOtpObject(_reason,this,otpErlangPid);
		else
			return toOtpObject(this,otpErlangPid);
	}
	public static final OtpErlangObject toOtpObject(Throwable th, OtpErlangPid otpErlangPid) {
		return toOtpObject(new OtpErlangString(th.getClass().getSimpleName()), th, otpErlangPid);
	}
	public static final OtpErlangObject toOtpObject(OtpErlangObject aReason,Throwable th, OtpErlangPid otpErlangPid) {
		ByteArrayOutputStream buff = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(buff);
		th.printStackTrace(ps);
		ps.flush();
		return new OtpErlangTuple(new OtpErlangObject[]{
				new OtpErlangAtom(th.getClass().getSimpleName()),
				otpErlangPid,
				aReason,
				new OtpErlangString(buff.toString()),
		});
	}
}
